﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HanGu.Services.Interface;
using HanGu.Entity;
using HanGu.Common;

namespace Hangu.WebClient.Controllers.Admin
{
    public class MemberInfoController : AdminBaseController
    {
        private static readonly IMemberInfo serviceMemberInfo = ServiceFactory.GetService<IMemberInfo>();
        private static readonly IDictionary serviceDict = ServiceFactory.GetService<IDictionary>();
        private static readonly IArea serviceArea = ServiceFactory.GetService<IArea>();
        private static readonly IMessage serviceMessage = ServiceFactory.GetService<IMessage>();
        private static readonly IChangeGradeRecorde serviceUpGrade = ServiceFactory.GetService<IChangeGradeRecorde>();
        protected static readonly IChangeChargeRecorde serviceChangeCharge = ServiceFactory.GetService<IChangeChargeRecorde>();
        protected static readonly IChangeGradeRecorde serviceGrade = ServiceFactory.GetService<IChangeGradeRecorde>();
        protected static readonly IChargeRecorde serviceCharge = ServiceFactory.GetService<IChargeRecorde>();

        public MemberInfoController()
        {

        }

        SelectList GetListFromDict(string groupName, bool IsSelectLabel = false)
        {
            var lst = serviceDict.GetByGroupName(groupName);
            if (IsSelectLabel)
            {
                lst.Insert(0, new Dictionary() { key = string.Empty, Value = "-----------请选择------------" });
            }
            SelectList sList = new SelectList(lst, "GenerateKey", "Value");
            return sList;
        }

        SelectList GetProvices(string proiceCode)
        {
            var provices = serviceArea.GetProvices();
            SelectList slist = new SelectList(provices, "AreaCode", "AreaName");
            if (string.IsNullOrEmpty(proiceCode))
            {
                proiceCode = provices != null && provices.Count > 0 ? provices[0].AreaCode : string.Empty;
            }
            ViewData["City"] = GetCitys(proiceCode);
            return slist;
        }

        SelectList GetCitys(string proiceCode)
        {
            var citys = serviceArea.GetCitys(proiceCode);
            SelectList slist = new SelectList(citys, "AreaCode", "AreaName");
            return slist;
        }
        SelectList GetMemberGrade()
        {
            SelectList selects = new SelectList(serviceDict.GetByGroupName("MemberGrade"), "GenerateKey", "Value");
            return selects;
        }
        /// <summary>
        /// 初始化 下拉列表
        /// </summary>
        /// <param name="proiceCode"></param>
        void GetSelectData(string proiceCode = null)
        {
            ViewData["SexList"] = GetListFromDict("sex");
            ViewData["IsMarry"] = GetListFromDict("marry");
            ViewData["Provice"] = GetProvices(proiceCode);
            ViewData["NativePlace"] = ViewData["Provice"];

            ViewData["Job"] = GetListFromDict("Job", true);
            ViewData["Trade"] = GetListFromDict("Trade", true);
            ViewData["Interest"] = GetListFromDict("Interest");
            ViewData["MemberGrade"] = GetListFromDict("MemberGrade");
            ViewData["Degree"] = GetListFromDict("Degree");
        }

        //
        // GET: /MemberInfo/

        public ActionResult Index()
        {
            ViewData["SexList"] = GetListFromDict("sex", true);
            ViewData["MemberGrade"] = GetListFromDict("MemberGrade", true);
            ViewData["Degree"] = GetListFromDict("Degree", true);
            return View(viewList, GetMemberInfoList());
        }

        [HttpPost]
        public ActionResult Index(FormCollection collection)
        {
            ViewData["SexList"] = GetListFromDict("sex", true);
            ViewData["MemberGrade"] = GetListFromDict("MemberGrade", true);
            ViewData["Degree"] = GetListFromDict("Degree", true);

            SearchParma.Suitabler = Request["Suitabler"];
            SearchParma.Lectcher = Request["Lectcher"];
            SearchParma.PalayAdress = Request["PalayAdress"];
            SearchParma.Degree = Request["Degree"];
            SearchParma.Pagination.RowCount = null;
            return View(viewList, GetMemberInfoList());
        }

        List<MemberInfo> GetMemberInfoList()
        {
            List<MemberInfo> MemberInfoList = serviceMemberInfo.GetAll(base.SearchParma);
            ViewData["RowCount"] = SearchParma.Pagination.RowCount;
            return MemberInfoList;
        }
        public ActionResult Detail(int id)
        {
            string proviceCode = string.Empty;
            MemberInfo memberInfo = new MemberInfo() { Pwd = Helper.MD5(Helper.DEFAULTPWD), GUID = Helper.GetGuid, CreateTime = DateTime.Now, Creator = CurentUser.UserName, UpdateTime = DateTime.Now, Updater = CurentUser.UserName };
            if (id > 0)
            {
                memberInfo = serviceMemberInfo.GetByID(id);
                proviceCode = memberInfo.Provice;
            }
            if (!memberInfo.NoEmail.HasValue) memberInfo.NoEmail = false;
            if (!memberInfo.NoSMS.HasValue) memberInfo.NoSMS = false;

            GetSelectData(proviceCode);
            if (string.IsNullOrEmpty(memberInfo.PicPath))
            {
                memberInfo.PicPath = "/Content/default.jpg";
            }

            SearchParma.IntObj1 = memberInfo.ID;
            ViewData["ChangeCharge"] = serviceChangeCharge.GetAll(SearchParma);//改变积分
            ViewData["ChangeGrade"] = serviceGrade.GetAll(SearchParma);
            ViewData["ChargeProduct"] = serviceCharge.GetAll(SearchParma);//积分兑换

            return View(viewCreate.Replace("create.", "detail."), memberInfo);
        }
        [HttpPost]
        public ActionResult Detail(int id,FormCollection collection)
        {
            string proviceCode = string.Empty;
            MemberInfo memberInfo = new MemberInfo() { Pwd = Helper.MD5(Helper.DEFAULTPWD), GUID = Helper.GetGuid, CreateTime = DateTime.Now, Creator = CurentUser.UserName, UpdateTime = DateTime.Now, Updater = CurentUser.UserName };
            if (id > 0)
            {
                memberInfo = serviceMemberInfo.GetByID(id);
                proviceCode = memberInfo.Provice;
            }
            if (!memberInfo.NoEmail.HasValue) memberInfo.NoEmail = false;
            if (!memberInfo.NoSMS.HasValue) memberInfo.NoSMS = false;

            GetSelectData(proviceCode);
            if (string.IsNullOrEmpty(memberInfo.PicPath))
            {
                memberInfo.PicPath = "/Content/default.jpg";
            }
            return View(viewCreate, memberInfo);
        }

        public ActionResult Create(int id)
        {
            string proviceCode = string.Empty;
            MemberInfo memberInfo = new MemberInfo() { Pwd = Helper.MD5(Helper.DEFAULTPWD), GUID = Helper.GetGuid, CreateTime = DateTime.Now, Creator = CurentUser.UserName, UpdateTime = DateTime.Now, Updater = CurentUser.UserName };
            if (id > 0)
            {
                memberInfo = serviceMemberInfo.GetByID(id);
                proviceCode = memberInfo.Provice;
            }
            if (!memberInfo.NoEmail.HasValue) memberInfo.NoEmail = false;
            if (!memberInfo.NoSMS.HasValue) memberInfo.NoSMS = false;

            GetSelectData(proviceCode);
            if (string.IsNullOrEmpty(memberInfo.PicPath))
            {
                memberInfo.PicPath = "/Content/default.jpg";
            }
            return View(viewCreate, memberInfo);
        }

        //
        // POST: /MemberInfo/Create

        [HttpPost]
        [ValidateInput(false)]
        public string Create(FormCollection collection)
        {
            try
            {

                MemberInfo memberInfo = new MemberInfo();
                TryUpdateModel(memberInfo, collection);
                memberInfo.NoEmail = collection["NoEmail"] != null;
                memberInfo.NoSMS = collection["NoSMS"] != null;
                memberInfo.Interest = Request["Interest"];
                bool tag = false;

                if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
                {
                    if (Request.Files[0].ContentType.IndexOf("image") >= 0)
                    {
                        UploadFileManage uploadFile = new UploadFileManage(Request.Files[0]);
                        uploadFile.ClassType = navTabId;
                        uploadFile.Save();
                        if (!uploadFile.Error)
                        {
                            //先删除旧图片
                            if (!string.IsNullOrEmpty(memberInfo.PicPath))
                            {
                                uploadFile.DeleteFile(memberInfo.PicPath);
                            }
                            memberInfo.PicPath = uploadFile.FileInfo["filepath"];

                            if (memberInfo.ID > 0)
                            {
                                tag = serviceMemberInfo.Update(memberInfo);
                            }
                            else
                            {
                                tag = serviceMemberInfo.Add(memberInfo);
                            }
                        }
                        else
                        {
                            ajaxStr = string.Format(ajaxStr, 300, uploadFile.Message, navTabId, "", "");
                        }
                    }
                    else
                    { ajaxStr = string.Format(ajaxStr, 300, ResourceManager.UnusefulImag, navTabId, "", ""); }
                }
                else
                {
                    if (memberInfo.ID > 0)
                    {
                        tag = serviceMemberInfo.Update(memberInfo);
                    }
                    else
                    {
                        tag = serviceMemberInfo.Add(memberInfo);
                    }

                }
                if (tag)
                {
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, navTabId, "", "closeCurrent");
                }
                else
                { ajaxStr = string.Format(ajaxStr, 300, ResourceManager.UnusefulImag, navTabId, "", ""); }

            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
            }
            return "{" + ajaxStr + "}";
        }

        //
        // GET: /MemberInfo/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /MemberInfo/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /MemberInfo/Delete/5
        [HttpPost]
        public string Delete(int id, string guid)
        {
            try
            {
                try
                {
                    FileManageController filemanage = new FileManageController();
                    filemanage.DeleteExecute(guid);
                }
                catch { }
                serviceMemberInfo.Delete(id);
                ajaxStr = string.Format(ajaxStr, 200, ResourceManager.DeleteSuccess, navTabId, "", "");
            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }

            return "{" + ajaxStr + "}";

        }
        [HttpPost]
        public string ResetPWD(int id, string guid)
        {
            try
            {
                var memberInfo = serviceMemberInfo.GetByID(id);
                if (!string.IsNullOrEmpty(memberInfo.UserName) && !string.IsNullOrEmpty(memberInfo.Email))
                {
                    int result = serviceMemberInfo.IsResetPwd(memberInfo.UserName, memberInfo.Email);
                    switch (result)
                    {
                        case -1:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,请联系管理员", "", "", "");
                            break;
                        case 0:
                            
                            SendMessage send = new SendMessage(true,true);
                            List<string> EmailTo = new List<string>();
                            EmailTo.Add(memberInfo.Email);
                            List<string> SMSTo = new List<string>();
                            SMSTo.Add(memberInfo.Tel);
                            send.EmailTo = EmailTo;
                            send.EmailCC = new List<string>();
                            send.SMSTo = SMSTo;
                            send.Title = "重设密码";
                            send.Content =string.Format( "尊敬的：{0}，您的用户名是：{1}，密码是：{2}，请您妥善保管！",
                                          memberInfo.RealName,
                                          memberInfo.UserName,
                                          Helper.DEFAULTPWD
                                          );
                            if (send.SendAll())
                            {
                                ajaxStr = string.Format(ajaxStr, 200, "重设且发送成功", "", "", "");
                            }
                            else
                            {
                                ajaxStr = string.Format(ajaxStr, 300, "重设成功，但发送失败，请检查邮件接口或短信接口设置是否正确。", "", "", "");
                            }
                            break;
                        case 1:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,用户名与邮箱不匹配", "", "", "");

                            break;
                        case 2:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,请联系管理员", "", "", "");
                            break;
                        default:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,请联系管理员", "", "", "");
                            break;
                    }
                }


            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }

            return "{" + ajaxStr + "}";

        }
        

    }
}
